/*
 * Copyright (C) 2007-2008 SlideMe client
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.slideme.android.manager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.*;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Activity that displays the top applications.
 */
public class TopApplicationsActivity extends Activity {

    private void updateContentList() {
        final Activity activity = this;

        SamApplication samApplication = (SamApplication) activity.getApplication();
        ApplicationManagerContext ctx = samApplication.getApplicationManagerContext();

        final ListView lv = (ListView) activity.findViewById(R.id.application_layout_listview);

        String[] from = new String[]{"displayName", "shortDescription", "vendorName", "iconFileUri", "category",
                "version", "creationDate"};
        int[] to = new int[]{R.id.application_list_displayName,
                R.id.application_list_shortDescription,
                R.id.application_list_vendor_name,
                R.id.application_list_image,
                R.id.application_list_category,
                R.id.application_list_version,
                R.id.application_list_date
        };
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(activity, R.layout.application_list_layout,
                ctx.getContentBundleRepository().fetchNotInstalledAsCursor(), from, to);

        //Binder for reading icons off of file-system
        adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
            public boolean setViewValue(View view, Cursor cursor, int i) {
                if (i < 0 || !(view instanceof ImageView)) return false;
                if (i != cursor.getColumnIndex("iconFileUri")) {
                    return false;
                }
                ImageView iconImageView = (ImageView) view;
                String fileUri = "/data/data/org.slideme.android.manager/files/"
                        + cursor.getString(i);

                BufferedInputStream bis;
                try {
                    bis = new BufferedInputStream(new FileInputStream(fileUri), 8192);
                } catch (FileNotFoundException e) {
                    Log.i("TopApplicationsActivity", "Could not find icon: Name =" + fileUri, e);
                    return false;
                }
                Bitmap bm = BitmapFactory.decodeStream(bis);
                try {
                    bis.close();
                } catch (IOException e) {
                    Log.d("TopApplicationsActivity", "Failed to read icon: Name = " + fileUri, e);
                    return false;
                }
                iconImageView.setImageBitmap(bm);
                return true;
            }
        });
        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView v, View view, int i, long j) {
                Intent intent = new Intent();
                intent.setClass(activity, ApplicationDisplayActivity.class);
                ApplicationDisplayActivity.CONTENT_ID = i + 1;//displayed in order
                activity.startSubActivity(intent, 1);
            }
        }
        );

        ImageButton myAppsView = (ImageButton) this.findViewById(R.id.application_layout_myapps_button);
        ImageButton settingsView = (ImageButton) this.findViewById(R.id.application_layout_settings_button);
        ImageButton applicationsView = (ImageButton) this.findViewById(R.id.application_layout_applications_button);
        ViewContext.setMenuViewListeners(myAppsView, settingsView, applicationsView, this);

    }

    private class CatalogUpdater2 extends Thread {

        private Activity activity;

        public CatalogUpdater2(Activity activity) {
            if (activity == null) {
                throw new IllegalArgumentException("activity");
            }
            this.activity = activity;
        }

        public void start() {
            pd = ProgressDialog.show(activity, "SlideME Application Manager", "Downloading Catalog...");
            pd.setIndeterminate(false);
            //   Message msg = new Message();
            //   h1.sendMessage(msg);
        }
    }


    private Handler h = new Handler() {
        @Override
        public void handleMessage(Message msg) {


        }
    };

    private Handler h1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // pd.dismiss();
            updateContentList();

        }
    };

    private static ProgressDialog pd;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        this.setContentView(R.layout.application_layout);

        // pd = ProgressDialog.show(this, "SlideME Application Manager", "Downloading Catalog...");
        // pd.setIndeterminate(false);

        SamApplication samApplication = (SamApplication) getApplication();
        if (samApplication == null) {
            Log.e("CatalogUpdater.start", "Sam Application not initialized");
            return;
        }
        updateContentList();
    }
}
